﻿using System;
using System.Windows.Controls.Primitives;
using System.Data.Services.Client;
using Coevery.ViewModel.EntityDataService;
using System.Linq;

namespace Coevery.ViewModel
{
    public class QuoteViewModel:BaseViewModel
    {
        public Guid QuoteId { get; set; }

        public Popup Popup { get; set; }

        public event EventHandler EnableButton;

        private DataServiceCollection<Quote> _quotes;
        public DataServiceCollection<Quote> Quotes 
        {
            get 
            {
                return _quotes;
            }
            set 
            {
                _quotes = value;
                _quotes.LoadCompleted += LoadQuoteData;
                OnPropertyChanged("Quotes");
            }
        }

        private DataServiceCollection<Note> _notes;
        public DataServiceCollection<Note> Notes 
        {
            get 
            {
                return _notes;
            }
            set 
            {
                _notes = value;
                _notes.LoadCompleted += LoadCommentData;
                OnPropertyChanged("Notes");
            }
        }

        public void LoadData() 
        {
          if(!Popup.IsOpen)
          {
              Popup.IsOpen = true;
              EnableButton.Invoke(false,null);
          }
          Quotes = new DataServiceCollection<Quote>(Context);
          Notes = new DataServiceCollection<Note>(Context);
          var query = (from cust in Context.Quotes.Expand("Owner").Expand("Customer").Expand("Opportunity")
                         where cust.QuoteId == QuoteId && cust.IsDeleted == false
                         select cust);
          Quotes.LoadAsync(query);          
        }

        private void LoadQuoteData(object sender, LoadCompletedEventArgs e) 
        {
            if (Quotes.Continuation != null) 
            {
                Quotes.LoadNextPartialSetAsync();
            }
            Notes.LoadAsync((from cust in Context.Notes.Expand("ModifiedBy") where cust.ObjectType == "Quote" && cust.ObjectId == QuoteId && cust.IsDeleted == false orderby cust.CreatedOn descending select cust));
        }

        private void LoadCommentData(object sender, LoadCompletedEventArgs e)
        {
            if (Notes.Continuation != null)
            {
                Notes.LoadNextPartialSetAsync();
            }
            Popup.IsOpen = false;
            EnableButton.Invoke(true, null);
        }
    }
}
